package com.dzsw.controller;

import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.core.FileItemFactory;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/non/multi")
public class NonMultipartController {

    @Value("${config.save-file-path}")
    private String saveFilePath;

    @RequestMapping("/ok")
    public String ok() {
        return "ok";
    }

    @PostMapping(value = "/s5")
    @ResponseBody
    public String upload5(HttpServletRequest request) throws IOException {
        return this.upload(request);
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public String upload(HttpServletRequest request) throws IOException {
        if (!JakartaServletFileUpload.isMultipartContent(request)) {
            throw new RuntimeException("bad request.");
        }
        DiskFileItemFactory factory = createDiskFileItemFactory();
        JakartaServletFileUpload upload = createJakartaServletFileUpload(factory);
        List<FileItem> itemList = upload.parseRequest(request);
        for (FileItem item : itemList) {
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                System.out.println(fieldName + ":" + fieldValue);
            } else {
                String nanoIdName = request.getAttribute("nanoIdName") != null ? (String) request.getAttribute("nanoIdName") : "";
                String pathAndName = saveFilePath + nanoIdName + "-" + item.getName();
                FileUtil.writeFromStream(item.getInputStream(), pathAndName);
            }
        }
        return "index";
    }

    private DiskFileItemFactory createDiskFileItemFactory() {
        DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
        return factory;
    }

    private JakartaServletFileUpload createJakartaServletFileUpload(FileItemFactory fileItemFactory) {
        JakartaServletFileUpload upload = new JakartaServletFileUpload(fileItemFactory);
        // 配置监听
        upload.setProgressListener((read, contentLen, items) -> {
            log.info("total length: {}, uploaded length: {}", contentLen, read);
        });
        upload.setHeaderCharset(StandardCharsets.UTF_8);
        // 设置文件最大值， -1L 标识无限制
        upload.setFileSizeMax(1024 * 1024);
        return upload;
    }
}
